<?php
function _teacher_filter_page(){
  $page = array();
  $page []= drupal_get_form('teacher_filter_form');
  return $page;
}

function _teacher_filter_results($cache_key){
  require_once(libraries_get_path('Vendor').'/autoload.php');
  $page = array();

  // results
  if(!($cached = cache_get($cache_key))) {
    drupal_not_found();
    drupal_exit();
  }
  $values = $cached->data;
  $page []= drupal_get_form('teacher_filter_form', $values);

  $role_id = 5;
  $query = db_select('users', 'u')
    ->fields('u', array('uid'))
    ->condition('ur.rid', $role_id)
    ->condition('u.status', 1);
  $query->join('users_roles', 'ur', 'ur.uid = u.uid');
  $query->join('profile', 'p', 'p.uid = u.uid');
  if($values['gender'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_gender', 'value', $values['gender']);
  if($values['age_start'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_birthday', 'value', _teacher_filter_age_to_datetime((int)$values['age_start']), '<=');
  if($values['age_end'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_birthday', 'value', _teacher_filter_age_to_datetime((int)$values['age_end']), '>=');
  if($values['hourly_rate_start'] && $values['hourly_rate_end']) {
    $hourly_opts = _teacher_filter_get_hourly_rate_options((int)$values['hourly_rate_start'], (int)$values['hourly_rate_end']);
    if(count($hourly_opts) == 0)
      $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_hourly_reate', 'value', '0-0');
    else
      $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_hourly_reate', 'value', $hourly_opts, 'IN');
  }
  if($values['nationality'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_nationality', 'iso2', $values['nationality']);
  if($values['partner'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_language_exchange', 'value', 1);
  if($values['chinese'])
    $query = Infinity\Query::fieldCondition($query, 'p.pid', 'profile2', 'teacher', 'field_teacher_chinese_level', 'value', $values['chinese']);
  $query->groupBy('u.uid')->orderBy('u.name');
  $uids = $query->extend('PagerDefault')->limit(20)->execute()->fetchCol();
  $users = user_load_multiple($uids);
  $user_view = array();
  foreach($users as $user) {
    $user_view []= user_view($user);
  }
  $page []= array(
    '#type' => 'fieldset',
    '#prefix' => '<div class="teacher-filter-results">',
    '#suffix' => '</div>',
    'users' => $user_view
  );

  return $page;
}

function teacher_filter_form($form, $form_state, $default_values = NULL){
  $form = array();
  $form['#attached']['css'] = array(
    drupal_get_path('module', 'teacher_filter') . '/teacher.css',
  );

  // hourly rate computed
  $form['hourly_rate_start'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#prefix' => '<span class="prefix">时薪</span>',
    '#suffix' => '<span class="suffix">到</span>',
    '#default_value' => '30'
  );
  $form['hourly_rate_end'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#suffix' => '<span class="suffix">￥</span>',
    '#default_value' => '600'
  );

  // load gender options
  $data = field_info_field('field_teacher_gender');
  $gender_opt = array('' => '男女');
  foreach($data['settings']['allowed_values'] as $key => $opt) {
    $gender_opt[$key]= $opt;
  }
  // gender
  $form['gender'] = array(
    '#type' => 'select',
    '#options' => $gender_opt
  );

  // load Nationality options
  $data = countries_get_countries();
  $nationality_opt = array();
  foreach($data as $key => $country) {
    $nationality_opt[$key] = $country->name;
  }
  // Nationality
  $form['nationality'] = array(
    '#type' => 'select',
    '#options' => array_merge(
      array('' => '所有国籍'),
      $nationality_opt
    ),
  );

  // age
  $form['age_start'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#prefix' => '<span class="prefix">年龄从</span>',
    '#suffix' => '<span class="suffix">到</span>',
    '#default_value' => '18'
  );
  $form['age_end'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#suffix' => '<span class="suffix">岁</span>',
    '#default_value' => '60'
  );

  //  Language Exchange Partner
  $form['partner'] = array(
    '#type' => 'checkbox',
    '#title' => '语言互助伙伴'
  );

  // load Spoken Mandarin Level options
  $data = field_info_field('field_teacher_chinese_level');
  $chinese_opt ['']= '汉语水平考试';
  foreach($data['settings']['allowed_values'] as $key => $value) {
    $chinese_opt[$key]= $value;
  }
  // Spoken Mandarin Level
  $form['chinese'] = array(
    '#type' => 'select',
    '#options' => $chinese_opt,
  );

  if($default_values) {
    // set default value
    foreach($default_values as $key => $value) {
      if(array_key_exists($key, $form)) {
        $form[$key]['#default_value'] = $value;
      }
    }
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => '去',
  );

  return $form;
}

function teacher_filter_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $cache_key = 'results-'.md5(serialize($values));
  cache_set($cache_key, $values);
  $form_state['redirect'] = 'teachers/results/'.$cache_key;
}

function _teacher_filter_get_hourly_rate_options($min, $max) {
  $data = field_info_field('field_teacher_hourly_reate');
  $options = $data['settings']['allowed_values'];
  $results = array();
  foreach($options as $key => $option) {
    list($opt_min, $opt_max) = explode('-', $option);
    if($min <= $opt_min && $max >= $opt_max) {
      $results[]= $key;
    }
  }
  return $results;
}

function _teacher_filter_age_to_datetime($age) {
  return date("Y-m-d H:i:s", time() - 31558150*$age);
}